/**
 * @author rubingqi@163.com
 * @description Login模块调用方法
 * @param [mui, window.login 调用变量名]
 */
(function ($, owner) {

    // 参数定义  
    // ==========================================================
//	var baseUrl = 'http://mtest.doctomate.com/orths/api/', //测试库
    var baseUrl = 'http://api.orthexpress.com/orths/api/', // 请求基础路径
	    uploadUrl = 'http://7xt1gr.com1.z0.glb.clouddn.com';
	
	owner.baseUrl = baseUrl;
    // Login 
    // ==========================================================

    owner.login = {
        /**
		 * 用户登录
		 */
        login: function (loginInfo, callback) {
            callback = callback || $.noop;
            loginInfo = loginInfo || {};
            loginInfo.account = loginInfo.account || '';
            loginInfo.password = loginInfo.password || '';

            if (loginInfo.account.length !== 11) {
                return callback('您的手机号长度有误');
            }
            if (loginInfo.password.length < 6) {
                return callback('密码最短为 6 个字符');
            }

            var data = JSON.stringify({
                dr_mobile: loginInfo.account,
                dr_psw: loginInfo.password,
                login_type: "PSW"
            });
            $.post(baseUrl + 'doctors/login.json', data, function (data) {
                if (data.code == 100) {
                	owner.storage.setUserInfo(data.data);
                	
                	var drId = owner.storage.getUserId(),
      					cId = plus.push.getClientInfo().clientid;
      				
      				app.net.post('doctors/update.json', {dr_id: drId, dr_cid: cId}, function(data){});
                	
                    return owner.storage.createState(loginInfo.account, callback);
                } else {
                    return callback('用户名或密码错误');
                }
            }, 'json');
        },

        /**
		 * 新用户注册
		 */
        reg: function (regInfo, callback) {
            callback = callback || $.noop;
            regInfo = regInfo || {};
            regInfo.account = regInfo.account || '';
            regInfo.password = regInfo.password || '';

            if (regInfo.password.length < 6) {
                return callback('密码最短需要 6 个字符');
            }

            var data = JSON.stringify({
                dr_mobile: regInfo.account,
                dr_psw: regInfo.password
            });

            $.post(baseUrl + 'doctors/create.json', data, function (data) {
                if (data.code == 100) {
                	owner.storage.setUserInfo(data.data);
                    return callback();
                } else {
                    return callback('您的输入有误，请重新输入');
                }
            });
        },

        /**
		 * 获取验证码 @continue  加入文字动态变化
		 */
        getPin: function (tel, callback) {
            callback = callback || $.noop;
            tel = tel || '';
            if (!tel || !(/^1[3|4|5|7|8]\d{9}$/.test(tel))) {
                return callback('请输入有效的手机号');
            }
            var data = { ac_mobile: tel };
            $.get(baseUrl + 'auth_codes/get.json', data, function (data) { });
        },

        /**
		 * 校验验证码
		 */
        checkPin: function (pinInfo, callback) {
            callback = callback || $.noop;
            pinInfo = pinInfo || {};
            pinInfo.tel = pinInfo.tel || '';
            pinInfo.pin = pinInfo.pin || '';

            if (!pinInfo.tel || !(/^1[3|4|5|7|8]\d{9}$/.test(pinInfo.tel))) {
                return callback('请输入有效的手机号');
            } else if (!pinInfo.pin) {
                return callback('验证码不能为空');
            }
			
            var data = { ac_mobile: pinInfo.tel, ac_code: pinInfo.pin };
            owner.net.get('auth_codes/check.json', data, function (data) {
                if (data && data.code === '100') {
                    return callback(data);
                } else {
                    return callback('请输入有效的验证码');
                }
            });
        },

        /**
		 * 找回密码
		 **/
        forgetPassword: function (email, callback) {
            callback = callback || $.noop;
            if (!checkEmail(email)) {
                return callback('邮箱地址不合法');
            }
            return callback(null, '新的随机密码已经发送到您的邮箱，请查收邮件。');
        },
		
		/**
		 * 认证用户信息
		 */
		approve : function(userInfo, callback){
			userInfo = userInfo || {};
			callback = callback || $.noop;
			var localInfo = owner.storage.getUserInfo();
			if(localInfo === {}) return callback('请登录后再试哟O(∩_∩)O~~');
			for(var i in userInfo){
				if(userInfo[i] === '' || userInfo[i] === undefined ) return callback('信息填写不完整');
			}
			
			var data = JSON.stringify({
			    dr_id : localInfo.dr_id,
			    dr_name : userInfo.name,
			    dr_hospital : userInfo.hos,
			    dr_title : userInfo.post,
			    dr_workcard_src : userInfo.picWork
			});
			
			
			$.post(baseUrl+'doctors/update.json', data, function(data){
				if(data.code == 100){
					owner.storage.setUserInfo(data.data);
					return callback();
				}else if(data.code == 400){
					return callback('您输入的信息已存在');
				}
			}, 'json');
			
		}

    };
    
    // Page 
    // =================================================================
    owner.page = {
        /** 
		 * @param {Object} info
		 * @param {Object} callback
		 */
        getMain: function (info, callback) {
            callback = callback || $.noop;
            info = info || {};
            info.page_num = info.page_num || 1;
            info.page_size = info.page_size || 5;

            var data = {
                page_num: info.page_num,
                page_size: info.page_size
            };

            $.get(baseUrl + 'news/show_list.json', data, function (json) {
                if (json.code == 100) {
                    //@continue  将用户信息存入本地
                    return callback(json.data);
                } else {
                    return callback(json.msg);
                }
            });
        },
        getSingleDetail: function (info, callback) {
            callback = callback || $.noop;
            info = info || {};
            info.news_id = info.news_id || '';
            info.dr_id = info.dr_id || '';

            var data = {
                news_id: info.news_id,
                dr_id: info.dr_id
            };

            $.get(baseUrl + 'news/show.json', data, function (json) {
                if (json.code == 100) {
                    //@continue  将用户信息存入本地
                    return callback(json.data);
                } else {
                    return callback(json.msg);
                }
            });
        },
        /** 
		 * @err
		 * @param {Object} info
		 * @param {Object} callback
		 */
        addCollect: function (info, callback) {
            callback = callback || $.noop;
            info = info || {};
            info.ncol_dr_id = info.ncol_dr_id || '';
            info.ncol_news_id = info.ncol_news_id || '';

            var data = JSON.stringify({
                ncol_dr_id: info.ncol_dr_id,
                ncol_news_id: info.ncol_news_id
            });
            
            $.ajax(baseUrl + 'news_collects/create.json', {
                data: data,
                dataType: 'json',//服务器返回json格式数据
                type: 'post',//HTTP请求类型
                success: function (data) {
                   if(data && data.code == 100){
                   	 return callback(data.data);
                   }
                },
                error: function (xhr, type, errorThrown) {
                    //异常处理；
                    console.log(xhr, type, errorThrown);
                    console.log(xhr.response);
                    console.log(xhr.status);
                }
            });

        },
        /**
		 * 删除收藏 
		 * @param {Object} info
		 * @param {Object} callback
		 */
        deleteCollect: function (info, callback) {
            callback = callback || $.noop;
            info = info || {};
            info.ncol_id = info.ncol_id || '';

            var data = JSON.stringify({
                ncol_id: info.ncol_id
            });
            
            $.post(baseUrl + 'news_collects/delete.json', data, function (data) {
                if (data.code == 100) {
                    //@continue  将用户信息存入本地
                    return callback(data);
                } else {
                    return callback(data);
                }
            }, 'json');
        },
        /**
		 * 获取术后随访记录
		 * @param {Object} info
		 * @param {Object} callback
		 */
        getInterviewRecord: function (info, callback, errorCallBack) {
            callback = callback || $.noop;
            errorCallBack = errorCallBack || $.noop;
            info = info || {};
            info.fo_dr_id = info.fo_dr_id || '';
            info.page_num = info.page_num || '1';
            info.page_size = info.page_size || '10';

            $.getJSON(baseUrl + 'c_followup/show_list', info, function (data) {
                if (data.code == 100) {
                    return callback(data.data);
                } else {
                    return errorCallBack(data.msg);
                }
            });
        },
        /**
         * 获取术后随访患者
         * @param {Object} info
         * @param {Object} callback
         */
        getInterviewPatient: function (info, callback, errorCallBack) {
            callback = callback || $.noop;
            errorCallBack = errorCallBack || $.noop;
            info = info || {};
            info.fo_dr_id = info.fo_dr_id || '';
            info.page_num = info.page_num || '1';
            info.page_size = info.page_size || '10';

            $.getJSON(baseUrl + 'c_patient/show_followup_patient_list', info, function (data) {
                if (data && data.code == 100) {
                    return callback(data.data);
                } else {
                    return errorCallBack(data.msg);
                }
            });
        },
        /**
         * 保存病历
         * @param {Object} info
         * @param {Object} callback
         */
        saveRecord: function (info, callback, errorCallBack) {
            $.ajax(baseUrl + "c_med_record/update", {
                data: JSON.stringify(info),
                dataType: 'json',//服务器返回json格式数据
                type: 'post',//HTTP请求类型
                timeout: 10000,//超时时间设置为10秒；
                success: function (data) {
                    if (data && data.code == 100) {
                        return callback(data.data);
                    } else {
                    	
                        return errorCallBack(data.code);
                    }
                },
                error: function (xhr, type, errorThrown) {
                    return errorCallBack(errorThrown);
                }
            });
        },
        /**
         * 获取病历记录
         * @param {Object} info
         * @param {Object} callback
         */
        getRecordList: function (info, callback, errorCallBack) {
            callback = callback || $.noop;
            errorCallBack = errorCallBack || $.noop;
            info = info || {};
            info.dr_id = info.dr_id;

            $.getJSON(baseUrl + 'c_med_record/show_list_by_dr_id', info, function (data) {
                if (data.code == 100) {
                    return callback(data.data);
                } else {
                    return errorCallBack(data.msg);
                }
            });
        },
        /**
         * 获取随访快码
         * @param {Object} callback
         */
        getInterCode: function (callback, errorCallBack) {
            callback = callback || $.noop;
            $.getJSON(baseUrl + 'c_followup/get_fast_code', function (data) {
                if (data && data.code == 100) {
                    return callback(data.data);
                } else {
                    if (errorCallBack) {
                        errorCallBack(data.msg);
                    }
                    else {
//                      alert(data.msg);
                    }
                }
            });
        },
        /**
         * 添加术后随访  
         * @param {Object} callback 
         */
        addInterview: function (info, callback, errorCallBack) {
            callback = callback || $.noop;
            info = info || {};
            $.ajax(baseUrl + "c_followup/create", {
                data: JSON.stringify(info),
                dataType: 'json',//服务器返回json格式数据
                type: 'post',//HTTP请求类型
                timeout: 10000,//超时时间设置为10秒；
                success: function (data) {
                    if (data && data.code == 100) {
			            $.get(baseUrl + 'c_followup/send_fast_code_sms', {pa_mobile: info.fo_patient_mobile,fast_code: info.fo_fast_code, fo_id: data.data.fo_id},function(data){},'json');
                        return callback(data.data);
                    } else {
                        if (errorCallBack) {
                            errorCallBack(data.msg);
                        }
                        else {
//                          alert(data.msg);
                        }
                    }
                },
                error: function (xhr, type, errorThrown) {
                    if (errorCallBack) {
                        errorCallBack(data.msg);
                    }
                    else {
//                      alert(data.msg);
                    }
                }
            });
            
        },
        /**
         * 添加医生反馈 
         * @param {Object} callback 
         */
        addReview: function (info, callback, errorCallBack) {
            callback = callback || $.noop;
            info = info || {};
            $.ajax(baseUrl + "c_surgery_post_pic_feedback/create", {
                data: JSON.stringify(info),
                dataType: 'json',//服务器返回json格式数据
                type: 'post',//HTTP请求类型
                timeout: 10000,//超时时间设置为10秒；
                success: function (data) {
                    if (data && data.code == 100) {
                        return callback(data.data);
                    } else {
                        if (errorCallBack) {
                            errorCallBack(data.msg);
                        }
                        else {
//                          alert(data.msg);
                        }
                    }
                },
                error: function (xhr, type, errorThrown) {
                    if (errorCallBack) {
                        errorCallBack(data.msg);
                    }
                    else {
//                      alert(data.msg);
                    }
                }
            });
        },
        /**
         * 添加一声反馈 
         * @param {Object} callback 
         */
        UPdateReview: function (info, callback, errorCallBack) {
            callback = callback || $.noop;
            info = info || {};
            $.ajax(baseUrl + "c_surgery_post_pic_feedback/update", {
                data: JSON.stringify(info),
                dataType: 'json',//服务器返回json格式数据
                type: 'post',//HTTP请求类型
                success: function (data) {
                    if (data && data.code == 100) {
                        return callback(data.data);
                    } else {
                        if (errorCallBack) {
                            errorCallBack(data.msg);
                        }
                        else {
//                          alert(data.msg);
                        }
                    }
                },
                error: function (xhr, type, errorThrown) {
                    if (errorCallBack) {
                        errorCallBack(xhr);
                    }
                    else {
//                      alert(xhr);
                    }
                }
            });
        }
    };
    // Storage 
    // =====================================================================

    owner.storage = {
        /**
		 * 用户信息和令牌存入本地
		 */
        createState: function (name, callback) { 
            var state = owner.storage.getState();
            state.account = name;
            state.token = "test150122";
            owner.storage.setState(state);
            return callback();
        },


        /**
		 * 获取当前状态
		 **/
        getState: function () {
            var stateText = localStorage.getItem('$state') || "{}";
            return JSON.parse(stateText);
        },

        /**
		 * 设置当前状态 
		 **/
        setState: function (state) {
            state = state || {};
            localStorage.setItem('$state', JSON.stringify(state));
        },



        /** 
		 * 设置应用本地配置
		 **/
        setSettings: function (settings) {
            settings = settings || {};
            localStorage.setItem('$settings', JSON.stringify(settings));
        },

        /**
		 * 获取应用本地配置
		 **/
        getSettings: function () {
            var settingsText = localStorage.getItem('$settings') || "{}";
            return JSON.parse(settingsText);
        },
       
        /**
         * 保存用户信息
         */
        setUserInfo : function(userInfo){
        	localStorage.removeItem('$userInfo');
        	userInfo = userInfo || {};
        	localStorage.setItem('$userInfo', JSON.stringify(userInfo));
        },
        
        /**
         * 获取用户信息
         */
        getUserInfo : function () {
            var userInfoText = localStorage.getItem('$userInfo') || "{}";
            return JSON.parse(userInfoText);
        },
        
        /**
         * 获取用户ID
         */
        getUserId : function() {
        	if(owner.storage.getUserInfo !== {}) return owner.storage.getUserInfo().dr_id;
        },
        
        /**
         * 清空用户信息
         */
        removeUserInfo : function(){
        	localStorage.removeItem('$userInfo');
        },
        
        /**
         * 保存用户信息
         */
        setGysUserInfo : function(userInfo){
        	localStorage.removeItem('$gysUserInfo');
        	userInfo = userInfo || {};
        	localStorage.setItem('$gysUserInfo', JSON.stringify(userInfo));
        },
        
        /**
         * 获取用户信息
         */
        getGysUserInfo : function () {
            var userInfoText = localStorage.getItem('$gysUserInfo') || "{}";
            return JSON.parse(userInfoText);
        },
        
        /**
         * 获取用户ID
         */
        getGysUserId : function() {
        	if(owner.storage.getGysUserInfo !== {}) return owner.storage.getGysUserInfo().actor_id;
        },
        
        /**
         * 清空用户信息
         */
        removeGysUserInfo : function(){
        	localStorage.removeItem('$gysUserInfo');
        }
        
        
    };

    // Utils
    // =======================================================================

    owner.utils = {
        /**
		 * 获取本地是否安装客户端
		 **/
        isInstalled: function (id) {
            if (id === 'qihoo' && mui.os.plus) {
                return true;
            }
            if (mui.os.android) {
                var main = plus.android.runtimeMainActivity();
                var packageManager = main.getPackageManager();
                var PackageManager = plus.android.importClass(packageManager)
                var packageName = {
                    "qq": "com.tencent.mobileqq",
                    "weixin": "com.tencent.mm",
                    "sinaweibo": "com.sina.weibo"
                }
                try {
                    return packageManager.getPackageInfo(packageName[id], PackageManager.GET_ACTIVITIES);
                } catch (e) { }
            } else {
                switch (id) {
                    case "qq":
                        var TencentOAuth = plus.ios.import("TencentOAuth");
                        return TencentOAuth.iphoneQQInstalled();
                    case "weixin":
                        var WXApi = plus.ios.import("WXApi");
                        return WXApi.isWXAppInstalled()
                    case "sinaweibo":
                        var SinaAPI = plus.ios.import("WeiboSDK");
                        return SinaAPI.isWeiboAppInstalled()
                    default:
                        break;
                }
            }
        },
        /**
         * 时间格式化
         **/
        formatData: function (strDateTime, intType) {
            var years, month, days, hours, minutes, seconds;
            var newDate, arrDate = new Array(),
                arrTime = new Array();

            if (strDateTime != undefined && strDateTime != null && strDateTime != "") {
                if (strDateTime instanceof Date) {
                    newDate = strDateTime;
                }
                else {
                    //获取日期和时间数组 
                    if (strDateTime.indexOf("-") != -1) {
                        var item = strDateTime.split(" ");
                        arrDate = item[0].toString().split("-");
                        arrTime = item[1].toString().split(":");
                    } else if (strDateTime.indexOf("/") != -1) {
                        var item = strDateTime.split(" ");
                        arrDate = item[0].toString().split("/");
                        arrTime = item[1].toString().split(":");
                    }
                    newDate = new Date(
                       parseInt(arrDate[0]),
                       parseInt(arrDate[1]),
                       parseInt(arrDate[2]),
                       parseInt(arrTime[0]),
                       parseInt(arrTime[1]),
                       parseInt(arrTime[2])
                   );
                }

                //处理数据 
                years = newDate.getFullYear();
                month = newDate.getMonth();
                month = month + 1;
                if (Number(month) < 10) month = "0" + month;
                days = newDate.getDate();
                if (Number(days) < 10) days = "0" + days;
                hours = newDate.getHours();
                if (Number(hours) < 10) hours = "0" + hours;
                minutes = newDate.getMinutes();
                if (Number(minutes) < 10) minutes = "0" + minutes;
                seconds = newDate.getSeconds();
                if (Number(seconds) < 10) seconds = "0" + seconds;

                switch (intType) {
                    case 'yyyy-MM-dd':
                        newDate = years + "-" + month + "-" + days;
                        break;
                    case 'MM-dd HH:mm':
                        newDate = month + "-" + days +
                            " " + hours + ":" + minutes;
                        break;
                    case 'HH:mm:ss':
                        newDate = hours + ":" + minutes + ":" + seconds;
                        break;
                    case 'HH:mm':
                        newDate = hours + ":" + minutes;
                        break;
                    case 'yyyy-MM-dd HH:mm':
                        newDate = years + "-" + month + "-" + days +
                            " " + hours + ":" + minutes;
                        break;
                    case 'yyyy/MM/dd':
                        newDate = years + "/" + month + "/" + days;
                        break;
                    case 'yyyy.MM.dd':
                        newDate = years + "." + month + "." + days;
                        break;
                    case 'MM/dd HH:mm':
                        newDate = month + "/" + days +
                            " " + hours + ":" + minutes;
                        break;
                    case 'yyyy/MM/dd HH:mm':
                        newDate = years + "/" + month + "/" + days +
                            " " + hours + ":" + minutes;
                        break;
                    case 'yy-MM-dd':
                        years = years.toString().substr(2, 2);
                        newDate = years + "-" + month + "-" + days;
                        break;
                    case 'yy/MM/dd':
                        years = years.toString().substr(2, 2);
                        newDate = years + "/" + month + "/" + days;
                        break;
                    case 'yyyy年MM月dd hh时mm分':
                        newDate = years + "年" + month + "月" + days +
                            " " + hours + "时" + minutes + "分";
                        break;
                    case 'yyyy-MM-dd HH:mm:ss':
                        newDate = years + "-" + month + "-" + days +
                            " " + hours + ":" + minutes + ":" + seconds;
                        break;
                }
            }
            return newDate;
        },
        /**
         * 从表单中获取实体对象
         **/
        getJsonFromForm: function (formID, callBack) {
            var resultObj = {};
            var inputArray = document.querySelectorAll("#" + formID + " input[name]");
            for (var i = 0; i < inputArray.length; i++) {
                var cur = inputArray[i];
                if (i < 3 && !cur.value) {
                    return callBack("请输入" + cur.previousElementSibling.textContent);
                    resultObj = null;
                    break;
                }
                resultObj[cur.name] = cur.value;
            }
            return resultObj;
        },
        /**
		 * localStorage存储与获取 
		 */
        localS: {
            set: function (key, value) {
                if (this.get(key) !== null)
                    this.remove(key);
                localStorage.setItem(key, value);
            },
            get: function (key) {
                var v = localStorage.getItem(key);
                return v === undefined ? null : v;
            },
            remove: function (key) { localStorage.removeItem(key); },
            clear: function () { localStorage.clear(); },
            each: function (fn) {
                var n = localStorage.length, i = 0, fn = fn || function () { }, key;
                for (; i < n; i++) {
                    key = localStorage.key(i);
                    if (fn.call(this, key, this.get(key)) === false)
                        break;
                    //如果内容被删除，则总长度和索引都同步减少
                    if (localStorage.length < n) {
                        n--;
                        i--;
                    }
                }
            }
        },
        
        collector : function(badge, target){
        	if((typeof badge !== 'string') || (typeof target !== 'object')) return console.error('Type error');
        	
        	var reg = new RegExp(badge),
        		tmp = {};
        		
        	for(var i in target){
		        if(reg.test(i)) tmp[i] = target[i]
		    }
		
		    return tmp;
        }
    };
    
    // Authority
    // ====================================================================
    owner.auth = {
    	isLogin : function(){
			if(owner.storage.getUserId()) return true;
			return false;
    	},
    	
    	isAudited : function(){
    		if(owner.storage.getUserInfo().dr_audit_status === 'AUDITED') return true;
    		return false;
    	}
    };
    
    // Image
    // =====================================================================
    owner.img = {
    	initPhotoSwipeFromDOM : function(gallerySelector){
    		
			// parse slide data (url, title, size ...) from DOM elements 
			// (children of gallerySelector)
			var parseThumbnailElements = function(el) {
			    var thumbElements = el.childNodes,
			        numNodes = thumbElements.length,
			        items = [],
			        figureEl,
			        childElements,
			        linkEl,
//			        img = new Image(),
					size,
			        item;
		
			    for(var i = 0; i < numNodes; i++) {
		
		
			        figureEl = thumbElements[i]; // <figure> element
		
			        // include only element nodes 
			        if(figureEl.nodeType !== 1) {
						continue;
			        }
		
					linkEl = figureEl.children[0]; // <a> element
					
//					img.src = linkEl.getAttribute('href');
					size = linkEl.getAttribute('data-size').split('x');
		
			        // create slide object
			        item = {
						src: linkEl.getAttribute('href'),
//						w: img.width,
//						h: img.height
						w: parseInt(size[0], 10),
						h: parseInt(size[1], 10)
			        };
		
			        
		
			        if(figureEl.children.length > 1) {
			        	// <figcaption> content
			          	item.title = figureEl.children[1].innerHTML; 
			        }
		 
			        if(linkEl.children.length > 0) {
			        	// <img> thumbnail element, retrieving thumbnail url
						item.msrc = linkEl.children[0].getAttribute('src');
			        } 
			       
					item.el = figureEl; // save link to element for getThumbBoundsFn
			        items.push(item);
			    }
		
			    return items;
			};
		
			// find nearest parent element
			var closest = function closest(el, fn) {
			    return el && ( fn(el) ? el : closest(el.parentNode, fn) );
			};
		
			// triggers when user clicks on thumbnail
			var onThumbnailsClick = function(e) {
			    e = e || window.event;
			    e.preventDefault ? e.preventDefault() : e.returnValue = false;
		
			    var eTarget = e.target || e.srcElement;
		
			    var clickedListItem = closest(eTarget, function(el) {
			        return el.tagName === 'FIGURE';
			    });
		
			    if(!clickedListItem) {
			        return;
			    }
		
		
			    // find index of clicked item
			    var clickedGallery = clickedListItem.parentNode,
			    	childNodes = clickedListItem.parentNode.childNodes,
			        numChildNodes = childNodes.length,
			        nodeIndex = 0,
			        index;
		
			    for (var i = 0; i < numChildNodes; i++) {
			        if(childNodes[i].nodeType !== 1) { 
			            continue; 
			        }
		
			        if(childNodes[i] === clickedListItem) {
			            index = nodeIndex;
			            break;
			        }
			        nodeIndex++;
			    }
		
		
		
			    if(index >= 0) {
			        openPhotoSwipe( index, clickedGallery );
			    }
			    return false;
			};
		
			// parse picture index and gallery index from URL (#&pid=1&gid=2)
			var photoswipeParseHash = function() {
				var hash = window.location.hash.substring(1),
			    params = {};
		
			    if(hash.length < 5) {
			        return params;
			    }
		
			    var vars = hash.split('&');
			    for (var i = 0; i < vars.length; i++) {
			        if(!vars[i]) {
			            continue;
			        }
			        var pair = vars[i].split('=');  
			        if(pair.length < 2) {
			            continue;
			        }           
			        params[pair[0]] = pair[1];
			    }
		
			    if(params.gid) {
			    	params.gid = parseInt(params.gid, 10);
			    }
		
			    if(!params.hasOwnProperty('pid')) {
			        return params;
			    }
			    params.pid = parseInt(params.pid, 10);
			    return params;
			};
		
			var openPhotoSwipe = function(index, galleryElement, disableAnimation) {
			    var pswpElement = document.querySelectorAll('.pswp')[0],
			        gallery,
			        options,
			        items;
		
				items = parseThumbnailElements(galleryElement);
		
			    // define options (if needed)
			    options = {
			        index: index,
		
					// define gallery index (for URL)
			        galleryUID: galleryElement.getAttribute('data-pswp-uid'),
		
			        getThumbBoundsFn: function(index) {
			            // See Options -> getThumbBoundsFn section of docs for more info
			            var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
			                pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
			                rect = thumbnail.getBoundingClientRect(); 
		
			            return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
			        },
		
			        // history & focus options are disabled on CodePen
		           	// remove these lines in real life: 
				   historyEnabled: false,
				   focus: false	
		
			    };
		
			    if(disableAnimation) {
			        options.showAnimationDuration = 0;
			    }
		
			    // Pass data to PhotoSwipe and initialize it
			    gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
			    gallery.init();
			};
		
			// loop through all gallery elements and bind events
			var galleryElements = document.querySelectorAll( gallerySelector );
		
			for(var i = 0, l = galleryElements.length; i < l; i++) {
				galleryElements[i].setAttribute('data-pswp-uid', i+1);
				galleryElements[i].onclick = onThumbnailsClick;
			}
		
			// Parse URL and open gallery if it contains #&pid=3&gid=1
			var hashData = photoswipeParseHash();
			if(hashData.pid > 0 && hashData.gid > 0) {
				openPhotoSwipe( hashData.pid - 1 ,  galleryElements[ hashData.gid - 1 ], true );
			}
    	}
    };
    
    // Form
    // ====================================================================
    owner.form = {
    	getInputEle : function(paId){
    		var parent = document.getElementById(paId);    
		    var elements = new Array();    
		    var tagElements = parent.getElementsByTagName('input');    
		    for (var j = 0; j < tagElements.length; j++){  
		         elements.push(tagElements[j]);  
		    }  
		    return elements;  
    	},
    	getCheckValue : function(ele){
    		if (ele.checked){
    			return {
    				subject_id : ele.dataset.sub,
    				options    : {
    					option_id : ele.dataset.opt,
    					option_score : ele.dataset.score
    				}
    			};
    		}
    	},
    	getInputValue : function(ele){
    		switch(ele.type.toLowerCase()){
    			case 'radio':
    				return this.getCheckValue(ele);
    			case 'range':
    				return {
    					subject_id : ele.dataset.sub,
    					subject_value : ele.value
    				};
    		}
    		return false;
    	},
    	serializeForm : function(formId){
    		var eles = this.getInputEle(formId),
    			commitData = {
    				dr_id : owner.storage.getUserId(),
    				rs_id : eles[0].dataset.rs,
    				subjects : []
    			};
    		
    		for (var i = 0; i < eles.length; i++) {    
		      var queryComponent = this.getInputValue(eles[i]);    
		      if (queryComponent)    
		        commitData.subjects.push(queryComponent);    
		    }
    		
    		return commitData;
    	},
    	getJsonFromForm: function (formID, callBack) {
            var resultObj = {};
            var inputArray = document.querySelectorAll("#" + formID + " input[name]");
            for (var i = 0; i < inputArray.length; i++) {
                var cur = inputArray[i];
                resultObj[cur.name] = cur.value;
            }
            return resultObj;
        }
    };

	// Net
	// =====================================================================
	owner.net = {
		get : function(url, info, successCB){
			url       = baseUrl + url;
			info 	  = info;
			successCB = successCB || $.noop;
			
			$.get(url, info, function(data){
				return successCB(data);
			}, 'json');
		},
		
		
		post : function(url, info, successCB){
			url       = baseUrl + url;
			info 	  = JSON.stringify(info);
			successCB = successCB || $.noop;
			
			$.post(url, info, function(data){
				return successCB(data);
			}, 'json');
		},
		
		ajax : function(url, info, method, successCB, errorCB){
			url       = baseUrl + url;
			info 	  = (method === 'post' ? JSON.stringify(info) : info);
			errorCB   = errorCB || $.noop;
			successCB = successCB || $.noop;
			
			console.log(url);
			console.log(method !== 'post' ? JSON.stringify(info) : info)
			mui.ajax(url,{
				data:info,
				dataType:'json',//服务器返回json格式数据
				type:method,//HTTP请求类型
				success:function(data){
					//服务器返回响应，根据响应结果，分析是否登录成功；
					return successCB(data);
				},
				error:function(xhr,type,errorThrown){
					//异常处理；
					console.log(xhr.status+'\n'+type+'\n'+errorThrown);
					return errorCB(xhr.response+'\n'+type+'\n'+errorThrown);
				}
			});
		}
	};
	
	// Broadcast
	// =========================================================================
	owner.bc = function(){
		var pages = plus.webview.all();
		for(var i in pages){
			$.fire(pages[i], 'start', null);
		}
	};
	
	// Test
	// ==========================================================================
	owner.t = function(data){
		alert(JSON.stringify(data))
	};

}(mui, window.app = {}));